#!/usr/bin/perl

package osregister;
use strict;
use modules::encode;
sub osregister {

    my ($dbh,$remote,$input,$csnum) = @_;
    my $sth;

#GET NICK INFO.
    $sth=$dbh->prepare("SELECT num,nick,auth,oper FROM ninfo WHERE num = '$$input[0]';");
    $sth->execute;
    my @ninfo;
    my $continue = 1;
    while (my @tmp = $sth->fetchrow_array) {
	if ($tmp[0] eq $$input[0]) {
	    @ninfo = @tmp;
	}
    }
    undef $continue;

#CHECK ISOP?

    $sth=$dbh->prepare("SELECT isop FROM onchan WHERE num = '$$input[0]'  AND code = '".encode::encode($$input[0])."' AND channel = '$$input[4]';");
    $sth->execute;
    my $isop = $sth->fetchrow_array;
#CHECK IS REG?
    $sth=$dbh->prepare("SELECT owner FROM channels where channel = '$$input[4]';");
    $sth->execute;
    my $isreg = $sth->fetchrow_array;

#CHECK IF HE OWNS 1 chann liao
    $sth=$dbh->prepare("SELECT owner FROM channels where owner = '$ninfo[2]';");
    $sth->execute;
    my $lamer = $sth->fetchrow_array;
    if ($$input[4] eq "") {
	print $remote "$csnum O $$input[0] :Syntax :REGISTER <\#Channel> [URL]\n";
    }
    elsif ($isop eq '0' || $isop eq "") {
	print $remote "$csnum O $$input[0] :Ops required in $$input[4].\n";
    }
    elsif ($isreg ne "") {
	print $remote "$csnum O $$input[0] :Error: Channel has been already registered by $isreg\n";
    }
    elsif ($ninfo[2] eq '0') {
	print $remote "$csnum O $$input[0] :You have to identify yourself first.\n";
    }
    elsif (length($$input[4]) > 20) {
	print $remote "$csnum O $$input[0] :Channel length exceeds db limits.\n";
    }
#    elsif ($ninfo[3] eq '0') {
#	print $remote "$csnum O $$input[0] :Access denied.\n";
#    }
    else {
	$sth=$dbh->prepare("INSERT INTO channels VALUES ('$$input[4]','$ninfo[2]','No Default topic set','nt','0','0',".time.",'$$input[5]',".time.");");
	$sth->execute;
	$sth=$dbh->prepare("INSERT INTO users VALUES ('$ninfo[2]','$$input[4]',500, 1, 0, 0)");
	$sth->execute;
	print $remote "$csnum J $$input[4]\n";
	my $bla = $csnum; chop $bla; chop $bla; chop $bla;
	print $remote "$bla M $$input[4] +o $csnum\n";
	print $remote "$csnum O $$input[0] :Channel registered.\n";
    }

}
1;
